package cn.psvmc.cxzapi.controller.alipay;

import cn.psvmc.cxzapi.config.ConfigKey;
import cn.psvmc.cxzapi.exception.ServiceException;
import cn.psvmc.cxzapi.mapper.order.TOrderBillMapper;
import cn.psvmc.cxzapi.mapper.order.TOrderMapper;
import cn.psvmc.cxzapi.mapper.store.*;
import cn.psvmc.cxzapi.model.customer.TCustomer;
import cn.psvmc.cxzapi.model.customer.TCustomerCard;
import cn.psvmc.cxzapi.model.order.TOrder;
import cn.psvmc.cxzapi.model.order.TOrderBill;
import cn.psvmc.cxzapi.model.store.*;
import cn.psvmc.cxzapi.service.alipay.AlipayCreate;
import cn.psvmc.cxzapi.service.customer.TCustomerCardService;
import cn.psvmc.cxzapi.service.order.TOrderService;
import cn.psvmc.cxzapi.service.system.ServiceUtil;
import cn.psvmc.cxzapi.util.CodeUtil;
import cn.psvmc.cxzapi.util.ToolUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.CreditRiskInfo;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.response.AlipayFundAuthOperationDetailQueryResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author ywx
 * @className AlipayController
 * @description 支付宝订阅消息
 * @date 2024/8/28 22:04
 **/
@RestController
@RequestMapping("/alipay")
@Slf4j
public class AlipayController {
    @Resource
    private TOrderMapper orderMapper;
    @Resource
    private TOrderBillMapper orderBillMapper;
    @Resource
    private ServiceUtil serviceUtil;
    @Resource
    private TOrderService orderService;
    @Resource
    private TAccountRecordMapper accountRecordMapper;
    @Resource
    private TAccountBillMapper accountBillMapper;
    @Resource
    private TAccountMapper accountMapper;
    @Resource
    private TCouponMapper couponMapper;
    @Resource
    private TCustomerCardService customerCardService;

    @RequestMapping("/notify")
    public String handleNotification(@RequestBody String notificationBody) {
        AlipayController.log.info("支付宝异步通知: {}", notificationBody);
        try {
            //这里需要根据支付宝的通知格式进行解析和验证
            LinkedHashMap<String, String> params = parseNotification(notificationBody);

            // 根据实际情况进行处理，例如更新订单状态
            if (verifySign(params)) {
                String msgMethod = params.get("msg_method");
                if (ToolUtils.isNotEmpty(msgMethod) && msgMethod.startsWith("alipay.user.opencard.")) {
                    return cardNotification(params);
                }
                if (ToolUtils.isNotEmpty(msgMethod) && msgMethod.startsWith("alipay.marketing.activity.message.")) {
                    return couponNotification(params);
                }
                //通知类型（fund_auth_freeze：资金预授权冻结，fund_auth_unfreeze：资金预授权解冻，trade_success：支付成功）
                String notifyType = params.get("notify_type");
                String tradeNo = params.get("trade_no");// 支付宝交易号
                //交易状态：（WAIT_BUYER_PAY：等待买家付款 TRADE_CLOSED：交易关闭，TRADE_SUCCESS：交易成功，TRADE_FINISHED：交易结束）
                String tradeStatus = params.get("trade_status");
                String status = params.get("status");
                String subject = params.get("subject");
                String orderCode = null;
                String bizContent = params.get("biz_content");
                Map<String, String> bizContentMap = new LinkedHashMap<>();
                if (ToolUtils.isNotEmpty(bizContent)) {
                    bizContentMap = JSON.parseObject(bizContent, Map.class);
                }
                String originInterface = bizContentMap.get("origin_interface");
                if ("alipay.fund.trans.order.changed".equals(msgMethod) && "alipay.fund.trans.uni.transfer".equals(originInterface)) {//单笔转账
                    String outBizNo = bizContentMap.get("out_biz_no");
                    String payDate = bizContentMap.get("pay_date");
                    String failReason = params.get("fail_reason");
                    status = bizContentMap.get("status");
                    zzOrCz(outBizNo, status, payDate, failReason);
                } else if ("trade_status_sync".equals(notifyType) && "充值".equals(subject)) {//充值
                    String outBizNo = params.get("out_trade_no");
                    String payDate = params.get("gmt_payment");
                    String failReason = params.get("fail_reason");
                    if ("TRADE_SUCCESS".equals(tradeStatus)) {
                        status = "SUCCESS";
                    } else {
                        status = "FAILED";
                    }
                    zzOrCz(outBizNo, status, payDate, failReason);
                } else if (ToolUtils.isNotEmpty(notifyType) && notifyType.startsWith("fund_auth_")) {//预授权
                    //资金操作类型（FREEZE：冻结，UNFREEZE：解冻，PAY：支付）
                    String operationType = params.get("operation_type");
                    //资金预授权冻结
                    String outOrderNo = params.get("out_order_no");//订单号
                    String authNo = params.get("auth_no");
                    if ("FREEZE".equals(operationType) && "SUCCESS".equals(status)) {
                        //资金预授权冻结成功
                        orderMapper.updateDepositStatus(outOrderNo, 1, 1, authNo);
                    } else if ("UNFREEZE".equals(operationType) && "SUCCESS".equals(status)) {
                        //资金预授权解冻成功
                        orderMapper.updateDepositStatus(outOrderNo, 2, 0, authNo);
                    } else if ("fund_auth_freeze.closed".equals(notifyType) && "SUCCESS".equals(status)) {
                        //资金预授权订单关闭
                        orderMapper.updateDepositStatus(outOrderNo, 0, 7, authNo);
                    } else if ("fund_auth_operation_cancel".equals(notifyType) && "SUCCESS".equals(status)) {
                        //资金预授权明细撤销
                        orderMapper.updateDepositStatus(outOrderNo, 2, 0, authNo);
                    }
                    orderCode = outOrderNo;
                } else if ("trade_status_sync".equals(notifyType)) {//支付
                    if (ToolUtils.isNotEmpty(params.get("gmt_refund")) && ToolUtils.isNotEmpty(params.get("refund_fee"))) {//退款已经处理过业务不在处理
                        return "success";
                    } else if ("押金转支付".equals(subject)) {//押金转支付
                        return "success";
                    }

                    // 支付成功
                    if (tradeStatus.equals("TRADE_SUCCESS")) {
                        int payType = 1;
                        TOrderBill bill = new TOrderBill();
                        bill.setTradeNo(tradeNo);
                        bill.setPayType(payType);
                        bill.setBillStatus(1);
                        bill.setTradeStatus(1);
                        String gmtPayment = params.get("gmt_payment");
                        LocalDateTime payTime = ToolUtils.strToLocalDateTime(gmtPayment);
                        bill.setRealDate(payTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                        bill.setPayTime(payTime);
                        orderBillMapper.updateBillStatus(bill);//更新账单支付状态

                        // 增加租金账户流水
                        serviceUtil.addAccountBillByTradeNo(tradeNo, 1, 31);

                        Integer orderId = orderMapper.getOrderPidByTradeNo(tradeNo);//获取买断账单的原始订单id
                        if (ToolUtils.isTrueInteger(orderId)) {
                            orderService.end(orderId);
                        }
                    } else if (tradeStatus.equals("TRADE_CLOSED")) {//交易关闭
                        TOrderBill bill = new TOrderBill();
                        bill.setTradeNo(tradeNo);
                        bill.setTradeStatus(3);
                        orderBillMapper.updateTradeStatus(bill);//更新账单交易状态
                    }
                } else if ("alipay.open.mini.order.changed".equals(msgMethod)) {//订单结果通知
                    String outOrderId = params.get("out_order_id");
                    if ("TIMEOUT_CLOSED".equals(status)) {
                        orderMapper.updateOrderStatusByCode(outOrderId, 7);//更新订单状态
                    } else if ("TRADE_FINISHED".equals(status)) {
                        orderMapper.updateOrderStatusByCode(outOrderId, 6);//更新订单状态
                    }
                    orderCode = outOrderId;
                } else if ("alipay.open.mini.order.settle.notify".equals(msgMethod)) {//订单结算通知
                    String outOrderId = params.get("out_order_id");
                    TOrderBill bill = new TOrderBill();
                    bill.setTransactionId(outOrderId);
                    bill.setTradeNo(tradeNo);
                    bill.setCutTime(ToolUtils.strToDateTime(params.get("settle_time")));
                    orderBillMapper.updateByTransactionId(bill);//更新结算信息
                }

                if (ToolUtils.isNotEmpty(orderCode)) {
                    AlipayFundAuthOperationDetailQueryResponse response = AlipayCreate.alipayFundAuthOperationDetailQuery(orderCode);//资金授权操作查询
                    if (response.isSuccess()) {
                        int preAuthType;
                        if ("CREDIT_AUTH".equals(response.getPreAuthType())) {
                            preAuthType = 1;
                        } else {
                            preAuthType = 2;
                        }
                        String creditRiskInfo = "";
                        CreditRiskInfo riskInfo = response.getCreditRiskInfo();
                        if (riskInfo != null) {
                            creditRiskInfo = riskInfo.getData();
                        }
                        TOrder order = new TOrder();
                        order.setOrderCode(orderCode);
                        order.setRestAmount(ToolUtils.objToDouble(response.getRestAmount()));
                        order.setPreAuthType(preAuthType);
                        order.setCreditRiskInfo(creditRiskInfo);
                        order.setTotalFreezeCreditAmount(response.getTotalFreezeCreditAmount());
                        order.setTotalFreezeFundAmount(response.getTotalFreezeFundAmount());
                        orderMapper.updateRestAmountByCode(order);//更新订单当前剩余冻结金额
                    }
                }
                return "success";
            } else {
                AlipayController.log.error("支付宝异步通知验签失败: {}", notificationBody);
                return "failure";
            }
        } catch (Exception e) {
            AlipayController.log.error("支付宝订阅消息处理失败: {}", e.getMessage());
            return "failure";
        }
    }

    //资金预授权通知
    @RequestMapping("/freeze_notify")
    public String freezeNotify(@RequestBody String notificationBody) {
        AlipayController.log.info("资金预授权异步通知: {}", notificationBody);
        try {
            //这里需要根据支付宝的通知格式进行解析和验证
            LinkedHashMap<String, String> params = parseNotification(notificationBody);

            String msgMethod = params.get("msg_method");
            //通知类型（fund_auth_freeze：资金预授权冻结，fund_auth_unfreeze：资金预授权解冻，trade_success：支付成功）
            String notifyType = params.get("notify_type");
            String tradeNo = params.get("trade_no");// 支付宝交易号
            //交易状态：（WAIT_BUYER_PAY：等待买家付款 TRADE_CLOSED：交易关闭，TRADE_SUCCESS：交易成功，TRADE_FINISHED：交易结束）
            String tradeStatus = params.get("trade_status");
            String status = params.get("status");
            String subject = params.get("subject");
            String orderCode = null;
            String bizContent = params.get("biz_content");
            if (ToolUtils.isNotEmpty(notifyType) && notifyType.startsWith("fund_auth_")) {//预授权
                //资金操作类型（FREEZE：冻结，UNFREEZE：解冻，PAY：支付）
                String operationType = params.get("operation_type");
                //资金预授权冻结
                String outOrderNo = params.get("out_order_no");//订单号
                String authNo = params.get("auth_no");
                if ("FREEZE".equals(operationType) && "SUCCESS".equals(status)) {
                    //资金预授权冻结成功
                    orderMapper.updateDepositStatus(outOrderNo, 1, 1, authNo);
                } else if ("UNFREEZE".equals(operationType) && "SUCCESS".equals(status)) {
                    //资金预授权解冻成功
                    orderMapper.updateDepositStatus(outOrderNo, 2, 0, authNo);
                } else if ("fund_auth_freeze.closed".equals(notifyType) && "SUCCESS".equals(status)) {
                    //资金预授权订单关闭
                    orderMapper.updateDepositStatus(outOrderNo, 0, 7, authNo);
                } else if ("fund_auth_operation_cancel".equals(notifyType) && "SUCCESS".equals(status)) {
                    //资金预授权明细撤销
                    orderMapper.updateDepositStatus(outOrderNo, 2, 0, authNo);
                }
                orderCode = outOrderNo;
            } else if ("trade_status_sync".equals(notifyType)) {//支付
                if (ToolUtils.isNotEmpty(params.get("gmt_refund")) && ToolUtils.isNotEmpty(params.get("refund_fee"))) {//退款已经处理过业务不在处理
                    return "success";
                } else if ("押金转支付".equals(subject)) {//押金转支付
                    return "success";
                }

                // 支付成功
                if (tradeStatus.equals("TRADE_SUCCESS")) {
                    int payType = 1;
                    TOrderBill bill = new TOrderBill();
                    bill.setTradeNo(tradeNo);
                    bill.setPayType(payType);
                    bill.setBillStatus(1);
                    bill.setTradeStatus(1);
                    String gmtPayment = params.get("gmt_payment");
                    LocalDateTime payTime = ToolUtils.strToLocalDateTime(gmtPayment);
                    bill.setRealDate(payTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                    bill.setPayTime(payTime);
                    orderBillMapper.updateBillStatus(bill);//更新账单支付状态

                    // 增加租金账户流水
                    serviceUtil.addAccountBillByTradeNo(tradeNo, 1, 31);

                    Integer orderId = orderMapper.getOrderPidByTradeNo(tradeNo);//获取买断账单的原始订单id
                    if (ToolUtils.isTrueInteger(orderId)) {
                        orderService.end(orderId);
                    }
                } else if (tradeStatus.equals("TRADE_CLOSED")) {//交易关闭
                    TOrderBill bill = new TOrderBill();
                    bill.setTradeNo(tradeNo);
                    bill.setTradeStatus(3);
                    orderBillMapper.updateTradeStatus(bill);//更新账单交易状态
                }
            }

            if (ToolUtils.isNotEmpty(orderCode)) {
                AlipayFundAuthOperationDetailQueryResponse response = AlipayCreate.alipayFundAuthOperationDetailQuery(orderCode);//资金授权操作查询
                if (response.isSuccess()) {
                    int preAuthType;
                    if ("CREDIT_AUTH".equals(response.getPreAuthType())) {
                        preAuthType = 1;
                    } else {
                        preAuthType = 2;
                    }
                    String creditRiskInfo = "";
                    CreditRiskInfo riskInfo = response.getCreditRiskInfo();
                    if (riskInfo != null) {
                        creditRiskInfo = riskInfo.getData();
                    }
                    TOrder order = new TOrder();
                    order.setOrderCode(orderCode);
                    order.setRestAmount(ToolUtils.objToDouble(response.getRestAmount()));
                    order.setPreAuthType(preAuthType);
                    order.setCreditRiskInfo(creditRiskInfo);
                    order.setTotalFreezeCreditAmount(response.getTotalFreezeCreditAmount());
                    order.setTotalFreezeFundAmount(response.getTotalFreezeFundAmount());
                    order.setCertifyPassed(1);
                    orderMapper.updateRestAmountByCode(order);//更新订单当前剩余冻结金额
                }
            }
            return "success";
        } catch (Exception e) {
            AlipayController.log.error("资金预授权消息处理失败: {}", e.getMessage());
            return "failure";
        }
    }

    //单笔转账或充值
    @Transactional(rollbackFor = Exception.class)
    public void zzOrCz(String outBizNo, String status, String payDate, String failReason) {
        TAccountRecord ar = accountRecordMapper.findByTransactionId(outBizNo);
        if (ar == null || ar.getStatus().equals(1)) {
            return;
        }
        if (status.equals("SUCCESS")) {
            Integer type = ar.getType();
            Double balance = ar.getBalance();
            Double amount = ar.getAmount();
            TAccount tAccount = new TAccount();
            tAccount.setAccountId(ar.getAccountId());
            double balance2;//交易后金额
            if (type.equals(2)) {//提现
                if (amount.compareTo(balance) > 0) {
                    throw new ServiceException("提现金额不能大于余额 ");
                }
                balance2 = ToolUtils.subtract(balance, amount);
            } else {
                balance2 = ToolUtils.add(balance, amount);
            }
            tAccount.setBalance(balance2);
            accountMapper.updateByAccountId(tAccount);

            Integer accountType = ar.getAccountType();
            int childType;
            String comm;
            if (accountType.equals(1)) {//租金账户
                if (type.equals(2)) {
                    childType = 21;
                    comm = "提现";
                } else {
                    childType = 11;
                    comm = "充值";
                }
            } else {
                if (type.equals(2)) {
                    childType = 22;
                    comm = "提现";
                } else {
                    childType = 12;
                    comm = "充值";
                }
            }

            TAccountBill bill = new TAccountBill();
            bill.setAccountId(ar.getAccountId());
            bill.setAccountType(ar.getAccountType());
            bill.setAmount(ar.getAmount());
            bill.setType(ar.getType());
            bill.setTransactionId(ar.getArid().toString());
            bill.setComm(comm);
            bill.setChildType(childType);
            bill.setInoutType(type);
            bill.setBalance(balance2);
            bill.setStoreid(ar.getStoreid());
            bill.setCreateid(-1);
            accountBillMapper.insert(bill);
            ar.setStatus(1);
            ar.setComm("支付成功");
        } else {
            if (ToolUtils.isEmpty(failReason)) {
                failReason = "支付失败";
            }
            ar.setComm(failReason);
        }
        ar.setPayDate(payDate);
        accountRecordMapper.updateSatusById(ar);
    }

    //解析参数
    private LinkedHashMap<String, String> parseNotification(String notificationBody) {
        LinkedHashMap<String, String> params = new LinkedHashMap<>();
        notificationBody = URLDecoder.decode(notificationBody, StandardCharsets.UTF_8);
        if (notificationBody.startsWith("{")) {
            notificationBody = notificationBody.substring(1, notificationBody.length() - 1);
        }
        // 分割字符串
        String[] pairs;
        if (notificationBody.contains(", ")) {
            pairs = notificationBody.split(", ");
        } else if (notificationBody.contains("&")) {
            pairs = notificationBody.split("&");
        } else {
            throw new ServiceException("通知格式错误");
        }
        for (String pair : pairs) {
            String[] keyValue = pair.split("=", 2); // 只分割成两部分
            if (keyValue.length == 2) {
                String key = keyValue[0];
                String value = keyValue[1];
                params.put(key, value);
            }
        }
        return params;
    }

    //验签
    private boolean verifySign(LinkedHashMap<String, String> params) throws AlipayApiException {
        //切记alipayPublicCertPath是支付宝公钥证书路径，请去open.alipay.com对应应用下载。
        String alipayPublicCertPath = ConfigKey.certPath + "alipayCertPublicKey_RSA2.crt";
        return AlipaySignature.rsaCertCheckV1(params, alipayPublicCertPath, "UTF-8", "RSA2");
    }

    /**
     * @Description 优惠券异步通知
     * @Date 2024/11/16 8:49
     * @Author YWX
     * @Param [notificationBody]
     * @Return java.lang.String
     **/
    public String couponNotification(LinkedHashMap<String, String> params) {
        String msgMethod = params.get("msg_method");
        AlipayController.log.info("支付宝优惠券异步通知: {}", params);
        try {
            Map<String, String> bizContent = JSON.parseObject(params.get("biz_content"), Map.class);
            String activityId = bizContent.get("activity_id");
            if ("alipay.marketing.activity.message.created".equals(msgMethod)) {//券活动创建通知
                serviceUtil.syncCoupon(activityId);
            } else if ("alipay.marketing.activity.message.expired".equals(msgMethod)) {//券过期
                couponMapper.updateStatusByActivityId(activityId, 2);
            } else if ("alipay.marketing.activity.message.stopped".equals(msgMethod)) {//券活动停止
                couponMapper.updateDeletedByActivityId(activityId);
            } else if ("alipay.marketing.activity.message.received".equals(msgMethod)) {//券领取
                String openId = bizContent.get("receive_open_id");
                String voucherCode = bizContent.get("voucher_code");
                String eventTime = bizContent.get("event_time");
                serviceUtil.addCustomerCoupon(activityId, openId, voucherCode, eventTime);
            }
            return "success";
        } catch (Exception e) {
            AlipayController.log.error("支付宝优惠券异步通知处理失败: {}", e.getMessage());
            return "failure";
        }
    }

    /**
     * @Description 会员卡异步通知
     * @Date 2025/1/4 19:08
     * @Author YWX
     * @Param [params]
     * @Return java.lang.String
     **/
    public String cardNotification(LinkedHashMap<String, String> params) {
        String msgMethod = params.get("msg_method");
        AlipayController.log.info("支付宝会员卡异步通知: {}", params);
        try {
            TCustomerCard card = JSON.parseObject(params.get("biz_content"), TCustomerCard.class);
            if ("alipay.user.opencard.result.notify".equals(msgMethod)) {//会员卡开卡结果通知
                customerCardService.add(card);
            }
            return "success";
        } catch (Exception e) {
            AlipayController.log.error("支付宝会员卡异步通知处理失败: {}", e.getMessage());
            return "failure";
        }
    }

    /**
     * @Description SPI服务接口请求
     * @Date 2025/1/5 0:35
     * @Author YWX
     * @Param [params, headers]
     * @Return java.lang.String
     **/
    @RequestMapping(value = "/isv/spi/service")
    @ResponseBody
    public String spiService(@RequestParam LinkedHashMap<String, String> params, @RequestHeader Map<String, String> headers) {
        log.info("ISV SPI服务接口请求参数: {}", params);
        // http响应结果载体
        JSONObject result = new JSONObject();
        // 业务处理结果载体
        JSONObject response = new JSONObject();

        // 提取spi接口定义的header参数,接口定义所有参数都需要参与验签（接口没有定义header参数则忽略这一步）
        String spiHeader = headers.get("spi_header");
        params.put("spi_header", spiHeader);

        try {
            if (verifySign(params)) {
                // 2、验签成功：处理业务逻辑，并构造业务处理结果
                JSONObject cardInfo = new JSONObject();
                cardInfo.put("external_card_no", CodeUtil.generateBillSequence());//商户外部会员卡卡号
                LocalDateTime openDate = LocalDateTime.now();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                cardInfo.put("open_date", openDate.format(formatter));//开卡时间
                cardInfo.put("valid_date", openDate.plusYears(100).format(formatter));//有效期
                cardInfo.put("template_id", params.get("template_id"));//会员卡模板id
                cardInfo.put("biz_card_no", params.get("biz_card_no"));
                // response中嵌套复杂类型数据结构场景
                response.put("card_info", cardInfo);
                List<Map> userInfos = JSON.parseArray(params.get("user_info"), Map.class);
                if (ToolUtils.isListNotEmpty(userInfos)) {
                    String openId = params.get("open_id");
                    String nickname = "OPEN_FORM_FIELD_NICKNAME";
                    String mobile = "OPEN_FORM_FIELD_MOBILE";
                    TCustomer customer = new TCustomer();
                    customer.setOpenid(openId);
                    for (Map<String, String> userInfo : userInfos) {
                        if (userInfo.containsKey(nickname)) {
                            customer.setCardNickname(userInfo.get(nickname));
                        } else if (userInfo.containsKey(mobile)) {
                            customer.setCardPhone(userInfo.get(mobile));
                        }
                    }
                    customerCardService.updateCardInfoByOpenId(customer);
                }

                response.put("code", "10000");
                response.put("msg", "Success");
            } else {
                // 3、验签失败：构造错误码
                response.put("code", "40004");
                response.put("msg", "Business Failed");
                response.put("sub_code", "ISV-VERIFICATION-FAILED");
                response.put("sub_msg", "验签失败");
            }
        } catch (AlipayApiException e) {
            response.put("code", "40004");
            response.put("msg", "Business Failed");
            response.put("sub_code", "INVALID_PARAMS");
            response.put("sub_msg", "无效参数");
        }
        // 4、业务处理结果加签 （可选，查看 服务基础配置 章节）
        // contentToSign为 {"code":"10000","msg":"Success","biz":"value","person":{"age":"18","height":"180"}}
        String contentToSign = response.toJSONString();
        String sign = null;
        try {
            sign = AlipaySignature.rsaSign(contentToSign, ConfigKey.privateKey, "UTF-8", "RSA2");
        } catch (AlipayApiException e) {
            response.put("code", "40004");
            response.put("msg", "Business Failed");
            response.put("sub_code", "SIGN_FAILED");
            response.put("sub_msg", "签名失败");
        }
        // 5、构造http响应结果
        result.put("sign", sign);
        //可选，查看 服务基础配置
        result.put("response", response);
        // 返回json格式响应报文
        return result.toJSONString();
    }
}
